/*
 * @Date: 2023-02-15 20:24:18
 * @LastEditTime: 2023-03-10 20:33:36
 * @FilePath: /hash-guess-game/src/store/useBalanceStore.ts
 * 介绍:用户余额全局缓存
 */
import { defineStore } from "pinia";
import { apiCoinlist } from "@@/api/module/sys";
import { sdkAutoFindBalance } from "@@/sdk/solana";
import {
  apiCoinGameBalance,
  apiDrawCoinInfo,
  DrawCoinInfo,
} from "@@/api/module/balance";

export default defineStore("StoreBalance", {
  //*全局仓库
  state: initState,
  //*全局函数
  actions: {
    async getCoinList() {
      const res = await apiCoinlist();
      if (!res) return;
      this.$patch((state) => {
        state.coinEnum = res;
      });
      return res;
    },
    async getDrawCoinInfo(
      index: StrNumber | void
    ): Promise<DrawCoinInfo.Res | void> {
      if (!index) return;
      if (isNaN(Number(index))) return;
      /**当前币种索引 */
      const currentIndex: number = Number(index);
      const coin: CoinEnum | undefined = this.coinEnum[currentIndex];
      if (!coin) return;
      const res = await apiDrawCoinInfo({ id: coin.id });
      if (!res) {
        console.warn("未查询到提币信息");
        return;
      }
      Object.assign(coin, res);
      return res;
    },
    /**获取游戏余额 */
    async getGameBalance(index: StrNumber | void): Promise<number | void> {
      if (!index) return;
      if (isNaN(Number(index))) return;
      /**当前币种索引 */
      const currentIndex: number = Number(index);
      const coin: CoinEnum | undefined = this.coinEnum[currentIndex];
      if (!coin) return;
      const res = await apiCoinGameBalance({ coin_id: coin.id });
      if (!res) {
        console.warn("未查询到游戏余额");
        return;
      }
      coin.gameBalance = Number(res.availbale);
      return coin.balance;
    },
    /**获取余额 */
    async getBalance(index: StrNumber | void): Promise<number | void> {
      if (!index) return;
      if (isNaN(Number(index))) return;
      /**当前币种索引 */
      const currentIndex: number = Number(index);
      const coin: CoinEnum | undefined = this.coinEnum[currentIndex];
      if (!coin) return;
      const res = await sdkAutoFindBalance(coin.contract_addr);
      if (!res.data) {
        console.warn("未查询到余额");
        return;
      }
      this.coinEnum[currentIndex].balance = res.data;
      return this.coinEnum[currentIndex].balance;
    },
    /**充币前置操作 */
    async drawCoinBefore(index: StrNumber | void): Promise<CoinEnum | void> {
      if (!index) return;
      if (isNaN(Number(index))) return;
      /**当前币种索引 */
      const currentIndex: number = Number(index);
      const coin: CoinEnum | undefined = this.coinEnum[currentIndex];
      if (!coin) return;
      await Promise.all([
        this.getGameBalance(coin.id),
        this.getDrawCoinInfo(coin.id),
      ]);
      return coin;
    },
    /**通过code获取币种 */
    getByCode(
      code: string
    ): (CoinEnum & { index: number | string }) | undefined {
      for (let key in this.coinEnum) {
        const value = this.coinEnum[key];
        if (code.toLocaleUpperCase() === value.code.toLocaleUpperCase()) {
          return {
            ...value,
            index: key,
          };
        }
      }
      console.warn(`未能获取到币种--getByCode${code}`);
    },
    /**通过id获取币种 */
    getById(id: Id): (CoinEnum & { index: number | string }) | undefined {
      for (let key in this.coinEnum) {
        const value = this.coinEnum[key];
        if (id === value.id) {
          return {
            ...value,
            index: key,
          };
        }
      }
      console.warn(`未能获取到币种--getById${id}`);
    },
  },
  //*计算属性
  getters: {},
  //*仓库数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        key: "StoreBalance",
        storage: localStorage, //指定储存位置
      },
    ],
  },
});
/**state类型定义 */
interface StoreBalance {
  coinEnum: CoinEnum[];
}
/**初始化pinia */
function initState(): StoreBalance {
  return {
    coinEnum: [
      {
        id: 5,
        code: "SOLRS",
        name: "SOLRS",
        image: "images/d0c9fc6cf9334c0ba581ddfc0ca1a5f0.png",
        is_withdraw: 1,
        contract_addr: "DkPn7EwX229HDWL9suY9o2GN6iov2pMpXhvujkUjav6A",
        format: 9,
        price: "0.000600",
        min: "4",
        max: "4000",
        logo: "https://solrimage.oss-ap-southeast-1.aliyuncs.com/images/d0c9fc6cf9334c0ba581ddfc0ca1a5f0.png",
      },
      {
        id: 6,
        code: "SOL",
        name: "SOL",
        image: "images/9421f34df3967dd18cba8dea09193b07.png",
        is_withdraw: 1,
        contract_addr: null,
        format: 9,
        price: "22.400000",
        min: "0.2",
        max: "20",
        logo: "https://solrimage.oss-ap-southeast-1.aliyuncs.com/images/9421f34df3967dd18cba8dea09193b07.png",
      },
      {
        id: 7,
        code: "HASH",
        name: "HASH",
        image: "images/QQ20221102-210048@2x.png",
        is_withdraw: 1,
        contract_addr: "Gu6yaN9RC8SogDcCkCpjAzjkVAL2vUMRYPP5dMaMeyaM",
        format: 9,
        price: "0.174800",
        min: "2",
        max: "4000",
        logo: "https://solrimage.oss-ap-southeast-1.aliyuncs.com/images/QQ20221102-210048@2x.png",
      },
      {
        id: 8,
        code: "USDW",
        name: "USDW",
        image: "images/usdtsolrs.png",
        is_withdraw: 1,
        contract_addr: "Am5hwEp5VBqXoeE5pRU47RTW6gYeFQ6ahi1j4ZVVeL2V",
        format: 9,
        price: "1.000000",
        min: "1",
        max: "1000",
        logo: "https://solrimage.oss-ap-southeast-1.aliyuncs.com/images/usdtsolrs.png",
      },
    ],
  };
}

/**币种数据枚举 */
export interface CoinEnum extends Coin, Partial<DrawCoinInfo.DrawInfo> {
  
  /**余额 */
  balance?: number;
  /**游戏余额,非钱包余额,游戏货币额 */
  gameBalance?: number;
  /**是否开放提币 */
  is_withdraw: number;
  /**最低竞猜金额 */
  min: StrNumber;
  /**最高竞猜金额 */
  max: StrNumber;
}
